const UserAiConversation = require("../models/UserAiConversation");
const chatSocketManager = require("../utils/chatSocketManager");

class ChatController {
  // 获取用户的聊天历史列表
  async getChatHistoryList(req, res) {
    try {
      const { uuid } = req.visitor;
      console.log(`获取聊天历史列表 - 用户: ${uuid}`);

      // 直接查询对话表，获取所有活跃对话
      const conversations = await UserAiConversation.findAll({
        where: {
          user_uuid: uuid,
          //   is_active: true, // 改为 false 可以查看已删除的对话，不加这个条件可以查看所有对话
        },
        attributes: [
          "id", // 添加主键字段
          "ai_person_id",
          "conversation_title",
          "ai_avatar",
          "last_message_content",
          "last_message_time",
          "conversation_data",
          "last_message_status",
        ],
        order: [["last_message_time", "DESC"]],
      });

      // 处理每个对话，检查最后一条AI消息状态并更新last_message_status
      const chatHistoryList = [];
      for (const conv of conversations) {
        // 检查conversation_data中的最后一条AI消息状态
        const messages = conv.conversation_data?.messages || [];
        let lastAiMessageStatus = null;
        let shouldUpdateStatus = false;
        let newLastMessageStatus = 0;

        // 从后往前查找最后一条AI消息
        for (let i = messages.length - 1; i >= 0; i--) {
          if (messages[i].sender === "ai") {
            lastAiMessageStatus = messages[i].status;
            break;
          }
        }

        // 检查最后一条AI消息状态并设置last_message_status
        if (lastAiMessageStatus === "Unread") {
          // 如果最后一条AI消息状态为"Unread"，设置last_message_status为1
          newLastMessageStatus = 1;
        } else {
          // 如果最后一条AI消息状态不是"Unread"（如"Success"、"streaming"等），设置last_message_status为0
          newLastMessageStatus = 0;
        }

        // 如果状态需要更新，则更新数据库
        if (conv.last_message_status !== newLastMessageStatus) {
          await conv.update({
            last_message_status: newLastMessageStatus,
          });
          console.log(
            `更新对话 ${conv.ai_person_id} 的last_message_status: ${conv.last_message_status} -> ${newLastMessageStatus} (最后AI消息状态: ${lastAiMessageStatus})`
          );

          // 发送WebSocket通知
          try {
            const chatHistoryItem = {
              id: conv.ai_person_id,
              name: conv.conversation_title || `AI助手 ${conv.ai_person_id}`,
              avatar:
                conv.ai_avatar ||
                conv.conversation_data?.metadata?.avatar_url ||
                "",
              timestamp: conv.last_message_time
                ? conv.last_message_time.toISOString()
                : new Date().toISOString(),
              lastMessage: conv.last_message_content || "",
              lastMessageStatus: newLastMessageStatus,
            };

            chatSocketManager.notifyChatHistoryUpdate(uuid, chatHistoryItem);
            console.log(
              `🔔 已发送WebSocket通知给用户: ${uuid}, 更新状态 ${conv.ai_person_id}: ${conv.last_message_status} -> ${newLastMessageStatus}`
            );
          } catch (notifyError) {
            console.error("WebSocket通知失败:", notifyError);
            // 通知失败不影响API响应
          }
        }

        // 转换为前端期望的格式
        chatHistoryList.push({
          id: conv.ai_person_id,
          name: conv.conversation_title || `AI助手 ${conv.ai_person_id}`,
          avatar:
            conv.ai_avatar ||
            conv.conversation_data?.metadata?.avatar_url ||
            "",
          timestamp: conv.last_message_time
            ? conv.last_message_time.toISOString()
            : new Date().toISOString(),
          lastMessage: conv.last_message_content || "",
          lastMessageStatus: newLastMessageStatus, // 添加last_message_status字段
        });
      }

      res.json({
        success: true,
        data: chatHistoryList,
      });
    } catch (error) {
      console.error("获取聊天历史列表失败:", error);
      res.status(500).json({
        success: false,
        message: "获取聊天历史失败",
      });
    }
  }

  // 获取特定AI的聊天记录
  async getChatHistory(req, res) {
    try {
      const { uuid } = req.visitor;
      const { id } = req.query;

      // 查找对话记录
      const conversation = await UserAiConversation.findOne({
        where: {
          user_uuid: uuid,
          ai_person_id: id,
          //   is_active: true,
        },
      });

      // 如果没有对话，返回空数据
      if (!conversation) {
        return res.json({
          success: true,
          data: {
            messages: [],
            sessionId: `${uuid}_${id}`, // 生成会话ID
          },
        });
      }

      // 获取消息列表
      const messages = conversation.conversation_data.messages || [];

      // 返回完整的消息数据
      const formattedMessages = messages;

      res.json({
        success: true,
        data: {
          messages: formattedMessages,
          sessionId: `${uuid}_${id}`,
        },
      });
    } catch (error) {
      console.error(`获取聊天记录${req.params.id}失败:`, error);
      res.status(500).json({
        success: false,
        message: "获取聊天记录失败",
      });
    }
  }

  // 保存聊天历史列表（更新对话元信息）
  async saveChatHistoryList(req, res) {
    try {
      const { uuid } = req.query;
      const chat_history_list = req.body;

      console.log(
        `📝 保存聊天历史列表 - 用户: ${uuid}, 数量: ${
          chat_history_list?.length || 0
        }`
      );

      // 批量处理每个对话
      for (const item of chat_history_list) {
        const { id, name, avatar, timestamp } = item;

        // 查找或创建对话
        const [conversation, created] = await UserAiConversation.findOrCreate({
          where: {
            user_uuid: uuid,
            ai_person_id: id,
          },
          defaults: {
            ai_avatar: avatar,
            conversation_data: {
              messages: [],
              metadata: {
                ai_name: name,
                avatar_url: avatar,
              },
            },
            conversation_title: name,
            is_active: true,
          },
        });

        // 如果是现有对话，更新元信息
        if (!created) {
          await conversation.update({
            conversation_title: name,
            ai_avatar: avatar,
            last_message_time: new Date(timestamp),
            is_active: true,
            conversation_data: {
              ...conversation.conversation_data,
              metadata: {
                ...conversation.conversation_data.metadata,
                ai_name: name,
                avatar_url: avatar,
              },
            },
          });

          // 添加WebSocket通知逻辑
          try {
            const chatHistoryItem = {
              id: id,
              name: name || `AI助手 ${id}`,
              avatar: avatar || "",
              timestamp: timestamp,
              lastMessage: conversation.last_message_content || "",
              lastMessageStatus: conversation.last_message_status || 0,
            };

            chatSocketManager.notifyChatHistoryUpdate(uuid, chatHistoryItem);
            console.log(
              `🔔 已发送WebSocket通知给用户: ${uuid}, 更新对话: ${id}`
            );
          } catch (notifyError) {
            console.error("WebSocket通知失败:", notifyError);
            // 通知失败不影响API响应
          }
        }
      }

      console.log(`✅ 聊天历史列表保存成功`);
      res.json({ success: true });
    } catch (error) {
      console.error("❌ 保存聊天历史列表失败:", error);
      res.status(500).json({
        success: false,
        message: "保存失败",
      });
    }
  }

  // 更新与特定AI的聊天记录
  async saveChatHistory(req, res) {
    const { sequelize } = require("../config/database");

    try {
      const { uuid, id, messages, sessionId } = req.body;

      console.log(
        `💾 保存聊天记录 - 用户: ${uuid}, AI: ${id}, 新增消息数: ${
          messages?.length || 0
        }`
      );

      // 如果没有消息内容，不进行任何操作
      if (!messages || messages.length === 0) {
        console.log(`⚠️ 没有消息内容，跳过保存 - 用户: ${uuid}, AI: ${id}`);
        return res.json({
          success: true,
          message: "没有消息内容，跳过保存",
        });
      }

      // 使用事务来确保并发安全
      const result = await sequelize.transaction(async (t) => {
        // 查找或创建对话（带锁）
        const [conversation, created] = await UserAiConversation.findOrCreate({
          where: {
            user_uuid: uuid,
            ai_person_id: id,
          },
          defaults: {
            ai_avatar: "",
            conversation_data: {
              messages: [],
              metadata: { ai_name: `AI助手 ${id}` },
            },
            is_active: true,
          },
          transaction: t,
          lock: t.LOCK.UPDATE, // 添加悲观锁
        });

        // 如果是已存在的记录，需要重新查询以获取最新数据（带锁）
        let lockedConversation = conversation;
        if (!created) {
          lockedConversation = await UserAiConversation.findOne({
            where: {
              user_uuid: uuid,
              ai_person_id: id,
            },
            transaction: t,
            lock: t.LOCK.UPDATE, // 添加悲观锁
          });
        }

        // 获取现有消息列表
        const existingMessages =
          lockedConversation.conversation_data.messages || [];

        // 将新消息添加到现有消息列表中
        const newMessages = messages || [];
        const updatedMessages = [...existingMessages, ...newMessages];

        // 获取最后一条消息的内容
        const lastMessageContent =
          updatedMessages.length > 0
            ? updatedMessages[updatedMessages.length - 1].content
            : "";

        // 更新对话数据
        lockedConversation.conversation_data = {
          ...lockedConversation.conversation_data,
          messages: updatedMessages,
          metadata: {
            ...lockedConversation.conversation_data.metadata,
            total_messages: updatedMessages.length,
            last_update_time: Date.now(),
          },
        };

        // 更新最后消息内容和时间
        lockedConversation.last_message_content = lastMessageContent;
        lockedConversation.last_message_time = new Date();

        // 保存更改（钩子会自动更新统计字段）
        await lockedConversation.save({ transaction: t });

        return lockedConversation;
      });

      console.log(`✅ 聊天记录保存成功 - 总消息数: ${result.total_messages}`);

      // 发送WebSocket通知
      try {
        // 1. 发送对话更新通知
        const chatHistoryItem = {
          id: id,
          name: result.conversation_title || `AI助手 ${id}`,
          avatar:
            result.ai_avatar ||
            result.conversation_data?.metadata?.avatar_url ||
            "",
          timestamp: result.last_message_time.toISOString(),
          lastMessage: result.last_message_content || "",
          lastMessageStatus: 0, // 默认设置为0，表示已读
        };

        chatSocketManager.notifyChatHistoryUpdate(uuid, chatHistoryItem);
        console.log(`🔔 已发送WebSocket通知给用户: ${uuid}`);
      } catch (notifyError) {
        console.error("WebSocket通知失败:", notifyError);
        // 通知失败不影响API响应
      }

      res.json({ success: true });
    } catch (error) {
      console.error(`❌ 保存聊天记录失败:`, error);
      res.status(500).json({
        success: false,
        message: "保存聊天记录失败",
      });
    }
  }

  // 删除聊天记录（硬删除）
  async deleteChatHistory(req, res) {
    try {
      const { uuid } = req.visitor; // 从认证中间件获取uuid
      const { id } = req.body; // 从请求体获取AI人物ID

      console.log(`🗑️ 开始删除聊天记录 - 用户: ${uuid}, AI: ${id}`);

      // 验证参数
      if (!id) {
        console.log(`❌ 缺少必要参数 id`);
        return res.status(400).json({
          success: false,
          message: "缺少必要参数 id",
        });
      }

      // 先查询记录是否存在
      const existingConversation = await UserAiConversation.findOne({
        where: {
          user_uuid: uuid,
          ai_person_id: id,
        },
      });

      console.log(
        `📋 查询结果 - 用户: ${uuid}, AI: ${id}, 存在: ${!!existingConversation}`
      );

      // 硬删除对话 - 从数据库中完全移除
      const result = await UserAiConversation.destroy({
        where: {
          user_uuid: uuid,
          ai_person_id: id,
        },
      });

      console.log(
        `🔢 删除结果 - 用户: ${uuid}, AI: ${id}, 删除行数: ${result}`
      );

      if (result === 0) {
        console.log(`⚠️ 对话不存在或已被删除 - 用户: ${uuid}, AI: ${id}`);
        return res.status(404).json({
          success: false,
          message: "对话不存在或已被删除",
        });
      }

      console.log(
        `✅ 删除聊天记录成功 - 用户: ${uuid}, AI: ${id} (已从数据库移除)`
      );

      // 可选：设置短期删除标记，防止立即重新创建（可以用Redis或内存缓存）
      // 这里只是记录日志，实际使用时可以根据需要实现
      console.log(
        `🔒 设置删除保护 - 用户: ${uuid}, AI: ${id}, 时间: ${new Date().toISOString()}`
      );

      res.json({
        success: true,
        message: "删除成功",
        deleted_records: result,
      });
    } catch (error) {
      console.error("❌ 删除聊天记录失败:", error);
      res.status(500).json({
        success: false,
        message: "删除失败",
        error:
          process.env.NODE_ENV === "development" ? error.message : undefined,
      });
    }
  }

  // 刷新聊天记录（只保留前两条消息）
  async refreshChatHistory(req, res) {
    try {
      // const { uuid } = req.visitor; // 从认证中间件获取uuid
      const { uuid, id } = req.body; // 从请求体获取AI人物ID

      console.log(`🔄 开始刷新聊天记录 - 用户: ${uuid}, AI: ${id}`);

      // 验证参数
      if (!id) {
        console.log(`❌ 缺少必要参数 id`);
        return res.status(400).json({
          success: false,
          message: "缺少必要参数 id",
        });
      }

      // 查找对话记录
      const conversation = await UserAiConversation.findOne({
        where: {
          user_uuid: uuid,
          ai_person_id: id,
        },
      });

      if (!conversation) {
        console.log(`⚠️ 对话不存在 - 用户: ${uuid}, AI: ${id}`);
        return res.status(404).json({
          success: false,
          message: "对话不存在",
        });
      }

      console.log(
        `📋 找到对话记录 - 用户: ${uuid}, AI: ${id}, 当前消息数: ${conversation.total_messages}`
      );

      // 获取当前的对话数据
      const currentData = conversation.conversation_data || {
        messages: [],
        metadata: {},
      };
      const currentMessages = currentData.messages || [];
      const currentMetadata = currentData.metadata || {};

      // 只保留前两条消息
      const keepMessages = currentMessages.slice(0, 2);

      // 更新metadata中的last_update_time
      const updatedMetadata = {
        ...currentMetadata,
        last_update_time: Date.now(),
      };

      // 构建新的对话数据
      const newConversationData = {
        messages: keepMessages,
        metadata: updatedMetadata,
      };

      // 获取当前时间
      const now = new Date();

      // 更新记录
      await conversation.update({
        conversation_data: newConversationData,
        last_accessed_at: now,
        // 注意：created_at 和 updated_at 由 Sequelize 自动管理
        // created_at 保持不变，updated_at 会自动更新为当前时间
      });

      // 重新获取更新后的记录以获取最新的时间戳
      const updatedConversation = await UserAiConversation.findByPk(
        conversation.id
      );

      console.log(`✅ 刷新聊天记录成功 - 用户: ${uuid}, AI: ${id}`);
      console.log(
        `📊 消息数量：${currentMessages.length} -> ${keepMessages.length}`
      );
      console.log(
        `⏰ 时间戳已更新：last_accessed_at: ${updatedConversation.last_accessed_at}, updated_at: ${updatedConversation.updatedAt}`
      );

      // 添加WebSocket通知逻辑
      try {
        const chatHistoryItem = {
          id: id,
          name:
            updatedConversation.conversation_title ||
            updatedConversation.conversation_data.metadata?.ai_name ||
            `AI助手 ${id}`,
          avatar:
            updatedConversation.ai_avatar ||
            updatedConversation.conversation_data.metadata?.avatar_url ||
            "",
          timestamp: updatedConversation.last_message_time
            ? updatedConversation.last_message_time.toISOString()
            : new Date().toISOString(),
          lastMessage: updatedConversation.last_message_content || "",
          lastMessageStatus: updatedConversation.last_message_status || 0,
        };

        chatSocketManager.notifyChatHistoryUpdate(uuid, chatHistoryItem);
        console.log(`🔔 已发送WebSocket通知给用户: ${uuid}, 刷新对话: ${id}`);
      } catch (notifyError) {
        console.error("WebSocket通知失败:", notifyError);
        // 通知失败不影响API响应
      }

      res.json({
        success: true,
        message: "刷新聊天记录成功",
        data: {
          original_message_count: currentMessages.length,
          remaining_message_count: keepMessages.length,
          last_accessed_at: updatedConversation.last_accessed_at,
          created_at: updatedConversation.createdAt,
          updated_at: updatedConversation.updatedAt,
          metadata: updatedMetadata,
        },
      });
    } catch (error) {
      console.error("❌ 刷新聊天记录失败:", error);
      res.status(500).json({
        success: false,
        message: "刷新聊天记录失败",
        error:
          process.env.NODE_ENV === "development" ? error.message : undefined,
      });
    }
  }

  // 同步所有聊天数据
  async syncAllData(req, res) {
    try {
      const { uuid } = req.visitor;
      const allData = req.body;

      console.log(`🔄 同步所有聊天数据 - 用户: ${uuid}`);

      // 获取chat_history_list
      const chatHistoryList = allData.chat_history_list || [];

      // 处理每个对话
      for (const item of chatHistoryList) {
        const { id: aiPersonId, name, avatar, timestamp, lastMessage } = item;

        // 获取对应的聊天记录
        const chatHistoryKey = `chat_history_${aiPersonId}`;
        const chatHistory = allData[chatHistoryKey];

        if (chatHistory && chatHistory.messages) {
          // 创建或更新完整对话
          const [conversation, created] = await UserAiConversation.findOrCreate(
            {
              where: {
                user_uuid: uuid,
                ai_person_id: aiPersonId,
              },
              defaults: {
                ai_avatar: avatar,
                conversation_data: {
                  messages: chatHistory.messages,
                  metadata: {
                    ai_name: name,
                    avatar_url: avatar,
                    session_id: chatHistory.sessionId,
                  },
                },
                conversation_title: name,
                is_active: true,
              },
            }
          );

          // 如果是现有对话，完整更新
          if (!created) {
            conversation.ai_avatar = avatar;
            conversation.conversation_data = {
              messages: chatHistory.messages,
              metadata: {
                ai_name: name,
                avatar_url: avatar,
                session_id: chatHistory.sessionId,
                sync_time: Date.now(),
              },
            };
            await conversation.save();
          }

          console.log(
            `✅ 同步对话 ${aiPersonId}: ${chatHistory.messages.length} 条消息`
          );

          // 添加WebSocket通知逻辑
          try {
            const chatHistoryItem = {
              id: aiPersonId,
              name: name || `AI助手 ${aiPersonId}`,
              avatar: avatar || "",
              timestamp: timestamp || new Date().toISOString(),
              lastMessage: lastMessage || "",
              lastMessageStatus: 0, // 默认为已读
            };

            chatSocketManager.notifyChatHistoryUpdate(uuid, chatHistoryItem);
            console.log(
              `🔔 已发送WebSocket通知给用户: ${uuid}, 同步对话: ${aiPersonId}`
            );
          } catch (notifyError) {
            console.error("WebSocket通知失败:", notifyError);
            // 通知失败不影响API响应
          }
        }
      }

      console.log(`🎉 全部数据同步完成`);
      res.json({ success: true });
    } catch (error) {
      console.error("❌ 同步数据失败:", error);
      res.status(500).json({
        success: false,
        message: "同步失败",
      });
    }
  }

  // 获取所有聊天数据（用于导出或备份）
  async getAllChatData(req, res) {
    try {
      const { uuid } = req.visitor;

      // 获取用户的所有对话
      const conversations = await UserAiConversation.findAll({
        where: {
          user_uuid: uuid,
          is_active: true,
        },
      });

      // 构建前端期望的数据格式
      const allData = {};

      // 生成chat_history_list
      allData.chat_history_list = conversations.map((conv) => ({
        id: conv.ai_person_id,
        name:
          conv.conversation_title ||
          conv.conversation_data.metadata?.ai_name ||
          `AI助手 ${conv.ai_person_id}`,
        avatar:
          conv.ai_avatar || conv.conversation_data.metadata?.avatar_url || "",
        timestamp: conv.last_message_time
          ? conv.last_message_time.toISOString()
          : new Date().toISOString(),
        lastMessage: conv.last_message_content || "",
      }));

      // 生成每个AI的聊天记录
      conversations.forEach((conv) => {
        const chatKey = `chat_history_${conv.ai_person_id}`;
        allData[chatKey] = {
          messages: conv.conversation_data.messages || [],
          sessionId:
            conv.conversation_data.metadata?.session_id ||
            `${uuid}_${conv.ai_person_id}`,
        };
      });

      console.log(
        `📤 导出聊天数据 - 用户: ${uuid}, 对话数: ${conversations.length}`
      );
      res.json({
        success: true,
        data: allData,
      });
    } catch (error) {
      console.error("❌ 获取聊天数据失败:", error);
      res.status(500).json({
        success: false,
        message: "获取数据失败",
      });
    }
  }

  // 编辑指定消息的状态
  async editChatStatus(req, res) {
    try {
      const { ai_person_id } = req.body;
      const user_uuid = req.visitor.uuid; // 从 token 中获取 uuid
      
      if (!user_uuid || !ai_person_id) {
        return res
          .status(400)
          .json({ success: false, message: "缺少必要参数 user_uuid 或 ai_person_id" });
      }
      
      // 查询对应的对话
      const conversation = await UserAiConversation.findOne({
        where: {
          user_uuid: user_uuid,
          ai_person_id: ai_person_id,
        },
      });
      
      if (!conversation) {
        return res
          .status(404)
          .json({ success: false, message: "未找到对应的对话记录" });
      }
      
      // 获取对话消息
      const conversationData = conversation.conversation_data || {
        messages: [],
      };
      const messages = conversationData.messages || [];
      
      console.log(`开始批量修改消息状态 - 用户: ${user_uuid}, AI: ${ai_person_id}, 消息数: ${messages.length}`);
      
      let changeCount = 0;
      
      // 批量修改所有消息的 status 为 "Success"
      messages.forEach(msg => {
        if (msg.status !== "Success") {
          msg.status = "Success";
          changeCount++;
        }
      });
      
      console.log(`修改了 ${changeCount} 条消息的状态为 Success`);
      
      // 更新 conversation_data 和 last_message_status
      conversation.set("conversation_data", {
        ...conversationData,
        messages: [...messages],
      });
      
      // 设置 last_message_status 为 0
      conversation.set("last_message_status", 0);
      
      // 保存修改
      await conversation.save({ fields: ["conversation_data", "last_message_status"] });
      
      // 重新查询以确保数据已更新
      const updatedConversation = await UserAiConversation.findByPk(conversation.id);
      
      // 发送WebSocket通知
      try {
        const chatHistoryItem = {
          id: ai_person_id,
          name: updatedConversation.conversation_title || `AI助手 ${ai_person_id}`,
          avatar:
            updatedConversation.ai_avatar ||
            updatedConversation.conversation_data?.metadata?.avatar_url ||
            "",
          timestamp: updatedConversation.last_message_time.toISOString(),
          lastMessage: updatedConversation.last_message_content || "",
          lastMessageStatus: 0, // 已读状态
        };

        chatSocketManager.notifyChatHistoryUpdate(user_uuid, chatHistoryItem);
        console.log(`🔔 已发送WebSocket通知给用户: ${user_uuid}`);
      } catch (notifyError) {
        console.error("WebSocket通知失败:", notifyError);
      }

      return res.json({ 
        success: true, 
        message: `批量更新成功，共修改 ${changeCount} 条消息状态为 Success，last_message_status 已设置为 0`,
        data: {
          user_uuid,
          ai_person_id,
          total_messages: messages.length,
          changed_messages: changeCount,
          last_message_status: 0
        }
      });
    } catch (error) {
      console.error("❌ 批量编辑消息状态失败:", error);
      res.status(500).json({ success: false, message: "批量编辑消息状态失败" });
    }
  }

  // 通知发送 WebSocket发送数据
  async testWebsocketNotify(req, res) {
    try {
      const { uuid } = req.body;
      console.log("应该向用户发起websocket数据", uuid);
      
      // 复用 getChatHistoryList 中的逻辑获取聊天历史数据
      // 直接查询对话表，获取所有活跃对话
      const conversations = await UserAiConversation.findAll({
        where: {
          user_uuid: uuid,
        },
        attributes: [
          "id", 
          "ai_person_id",
          "conversation_title",
          "ai_avatar",
          "last_message_content",
          "last_message_time",
          "conversation_data",
          "last_message_status",
        ],
        order: [["last_message_time", "DESC"]],
      });

      // 处理每个对话，检查最后一条AI消息状态
      const chatHistoryList = [];
      for (const conv of conversations) {
        // 检查conversation_data中的最后一条AI消息状态
        const messages = conv.conversation_data?.messages || [];
        let lastAiMessageStatus = null;
        let newLastMessageStatus = 0;

        // 从后往前查找最后一条AI消息
        for (let i = messages.length - 1; i >= 0; i--) {
          if (messages[i].sender === "ai") {
            lastAiMessageStatus = messages[i].status;
            break;
          }
        }

        // 检查最后一条AI消息状态并设置last_message_status
        if (lastAiMessageStatus === "Unread") {
          newLastMessageStatus = 1;
        } else {
          newLastMessageStatus = 0;
        }

        // 转换为前端期望的格式
        chatHistoryList.push({
          id: conv.ai_person_id,
          name: conv.conversation_title || `AI助手 ${conv.ai_person_id}`,
          avatar:
            conv.ai_avatar ||
            conv.conversation_data?.metadata?.avatar_url ||
            "",
          timestamp: conv.last_message_time
            ? conv.last_message_time.toISOString()
            : new Date().toISOString(),
          lastMessage: conv.last_message_content || "",
          lastMessageStatus: newLastMessageStatus, 
        });
      }
      
      // 通过WebSocket发送完整的聊天历史列表
      chatSocketManager.notifyFullChatHistoryList(uuid, chatHistoryList);
      console.log(`✅ WebSocket已发送完整聊天历史列表给用户: ${uuid}, 共${chatHistoryList.length}条记录`);
      
      res.json({
        success: true,
        message: `已通过WebSocket发送完整聊天历史列表，共${chatHistoryList.length}条记录`,
        uuid,
      });
    } catch (error) {
      console.error("❌ WebSocket发送聊天历史数据失败:", error);
      res.status(500).json({ 
        success: false, 
        message: "WebSocket发送数据失败", 
        error: process.env.NODE_ENV === "development" ? error.message : undefined 
      });
    }
  }
}

module.exports = new ChatController();
